package com.tangula.web.kashine.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.tangula.controller.PagingQueryController;
import com.tangula.controller.ReturnRespController;
import com.tangula.core.Context;
import com.tangula.core.Controller;
import com.tangula.web.config.auth.Ignore;
import com.tangula.web.form.DefaultPagingBody;
import com.tangula.web.form.IdForm;
import com.tangula.web.kashine.business.BusinessFailException;
import com.tangula.web.kashine.business.ClassBusiness;
import com.tangula.web.kashine.business.ClassStudentRefBusiness;
import com.tangula.web.kashine.business.ScheduleBusiness;
import com.tangula.web.kashine.business.StudentAwardBusiness;
import com.tangula.web.kashine.business.TeacherBusiness;
import com.tangula.web.kashine.entity.AccountEntity;
import com.tangula.web.kashine.entity.AwardEntity;
import com.tangula.web.kashine.entity.BaseRespEntity;
import com.tangula.web.kashine.entity.ClassEntity;
import com.tangula.web.kashine.entity.ClassStudentRefEntity;
import com.tangula.web.kashine.entity.CostListForm2;
import com.tangula.web.kashine.entity.DeleteStudentForm;
import com.tangula.web.kashine.entity.IdNameDescIconForm;
import com.tangula.web.kashine.entity.LoadTeacherStudentForm;
import com.tangula.web.kashine.entity.LoadTopForm;
import com.tangula.web.kashine.entity.PagableForm;
import com.tangula.web.kashine.entity.SendAwardForm;
import com.tangula.web.kashine.entity.SendMoneyForm;
import com.tangula.web.kashine.entity.SendMoneyScheduleEntity;
import com.tangula.web.kashine.entity.StudentAwardRecordEntity;
import com.tangula.web.kashine.entity.TeacherPageableForm;
import com.tangula.web.kashine.entity.TeacherSendMoneyForm;
import com.tangula.web.kashine.entity.UpDateStudentForm;

@RestController
@RequestMapping("/teacherController")
@ResponseBody
public class TeacherController
		implements Controller<Context>, ReturnRespController, AuthController, PagingQueryController {
	@Autowired
	TeacherBusiness teacherBusiness;
	@Autowired
	ClassBusiness classBusiness;
	@Autowired
	ClassStudentRefBusiness classStudentBusiness;
	@Autowired
	StudentAwardBusiness studentAwardBusiness;

	@Autowired
	ScheduleBusiness bizSchedule;
	
	/**
	 * 教师注册
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/postRegister", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> postRegister(@RequestBody AccountEntity account) {

		return returnSuccess(teacherBusiness.register(account) != null);
	}

	/**
	 * 教师查看班级列表
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/loadAllClassOfTeacher", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<ClassEntity>>> putClassList() {
		DefaultPagingBody<ClassEntity> res = new DefaultPagingBody<ClassEntity>(1, 999);
		res.fill(classBusiness.loadAllClasses(loadCurrentAccount().getId(), toPageRequestDescId(1, 999)));
		return returnSuccess(res);
	}

	/**
	 * 教师查看班级中的学生
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/loadTeacherAllStudent", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<UpDateStudentForm>>> putLoadStudentInClass(
			@RequestBody LoadTeacherStudentForm clas) {
		return returnSuccess(classStudentBusiness.showStudentInClass(clas));
	}

	/**
	 * 教师更改班级中学生的信息
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/updateClassMember", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> postUpdateClassMember(@RequestBody ClassStudentRefEntity form) {
		return returnSuccess(classStudentBusiness.changeClassStudent(form) != null);
	}

	/**
	 * 教师删除选定的学生
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/removeClassMember", consumes = "application/json", method = { RequestMethod.DELETE })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> postDeleteStudentFromClass(
			@RequestBody DeleteStudentForm classStudent) {
		return returnSuccess(classStudentBusiness.deleteStudentFromClass(classStudent));
	}

	/**
	 * 教师创建奖励
	 * 
	 * @param user .
	 * @return .!!!!!!!!!!!!!!!!!!!!!!
	 */
	@RequestMapping(value = "/putCreatAwrd", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> putCreatAwrd(@RequestBody StudentAwardRecordEntity studentAward) {
		return returnSuccess(studentAwardBusiness.findProductByTeacher(studentAward) != null);
	}

	/**
	 * 教师给学生发送奖励
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/putAwardToStudent", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> putAwardToStudent(@RequestBody SendAwardForm send) {
		return returnSuccess(studentAwardBusiness.saveAwardToStudent(send));
	}

	/**
	 * 教师给学生发送基金
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/sendMoney", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> putMoneyToStudent(@RequestBody SendMoneyForm send) {
		try {
			return returnSuccess(teacherBusiness.sendMoneyToStudent(send));
		} catch (BusinessFailException ex) {
			return returnBusinessFail(ex, null);
		}
	}
	
	/**
	 * 教师给学生发送基金
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/sendMoneySchedule", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> sendMoneySchedule(@RequestBody SendMoneyForm send) {
		try {
			return returnSuccess(bizSchedule.createOrSave(SendMoneyScheduleEntity.fromTeacherSendMoneyForm(send)));
		} catch (BusinessFailException ex) {
			return returnBusinessFail(ex, null);
		}
	}

	/**
	 * 教师查看历史记录
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/loadSendMoneyLatestHistory", consumes = "application/json", method = {
			RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<TeacherSendMoneyForm>>> postShowHistory(
			@RequestBody TeacherPageableForm teacher) {
		return returnSuccess(teacherBusiness.showHistory(teacher));
	}

	/**
	 * 教师添加班级
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/createClassOfTeacher", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> putCreatClass(@RequestBody ClassEntity claz) {
		claz.setOwnerTeacher(loadCurrentAccount().getId());
		return returnSuccess(classBusiness.addClass(claz) != null);
	}

	/**
	 * 教师更改班级信息
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/updateClassInfo", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> updateClassInfo(@RequestBody ClassEntity claz) {
		logDebug(JSONObject.toJSONString(claz));
		return returnSuccess(classBusiness.updateClassInfo(claz) != null);
	}

	/**
	 * 教师查看花钱最多和获得奖励最多的学生
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/loadTopItems", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<LoadTopForm>> loadTopItems(@RequestBody String teacherId) {
		teacherId = loadCurrentAccount().getId();
		return returnSuccess(classBusiness.loadTopItems(teacherId));
	}

	/**
	 * 教师删除班级
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/removeClass", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> removeClass(@RequestBody String classId) {
		return returnSuccess(classBusiness.removeClass(classId));
	}

	/**
	 * 教师查看课程销售情况
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/loadTeacherHomeCostList", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<CostListForm2>>> loadTeacherHomeCostList(
			@RequestBody TeacherPageableForm teacher) {
		return returnSuccess(classBusiness.loadTeacherHomeCostList(teacher));
	}

	/**
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/classes", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<ClassEntity>>> classes(@RequestBody PagableForm form) {
		String teacherId = loadCurrentAccount().getId();
		DefaultPagingBody<ClassEntity> res = new DefaultPagingBody<ClassEntity>(form);
		Page<ClassEntity> page = classBusiness.loadAllClasses(teacherId,
				form.toPageRequest(new Sort.Order(Direction.DESC, "id")));
		res.fill(page);
		return returnSuccess(res);
	}

	/**
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/classes/{id}", consumes = "application/json", method = { RequestMethod.DELETE })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> classes(@PathVariable("id") String classId) {
		String teacherId = loadCurrentAccount().getId();
		boolean res = classBusiness.removeTeacherClass(teacherId, classId);
		return returnSuccess(res);
	}

	/**
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/createTeacherAward", consumes = "application/json", method = { RequestMethod.PUT })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> createTeacherAward(@RequestBody AwardEntity entity) {
		String teacherId = loadCurrentAccount().getId();
		entity.setOwnerTeacher(teacherId);
		return returnSuccess(teacherBusiness.createAward(entity));
	}

	/**
	 * 教师查看课程销售情况
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/awards/all", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<AwardEntity>>> loadAwardsAll(@RequestBody PagableForm form) {
		DefaultPagingBody<AwardEntity> res = new DefaultPagingBody<AwardEntity>(form);
		logDebug(JSONObject.toJSONString(form));
		Page<AwardEntity> page = teacherBusiness.loadAllAwards(loadCurrentAccount().getId(),
				form.toPageRequest(new Sort.Order(Direction.DESC, "id")));
		res.fill(page);
		return returnSuccess(res);

	}

	/**
	 * 教师查看课程销售情况
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/students/outofclass/{classId}", method = { RequestMethod.GET })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<AccountEntity>>> loadOutOfClassStudents(
			@PathVariable("classId") String classId, @RequestParam("index") int index, @RequestParam("size") int size) {
		// logDebug("classId:"+classId+";index:"+index+",size:"+size);
		DefaultPagingBody<AccountEntity> res = new DefaultPagingBody<AccountEntity>(index, size);
		Page<AccountEntity> page = teacherBusiness.loadOutOfClassStudent(loadCurrentAccount().getId(), classId,
				toPageRequestDescId(index, size));
		res.fill(page);
		// logDebug(JSONObject.toJSONString(res));
		return returnSuccess(res);

	}

	@RequestMapping(value = "/classes/{classId}/{studentId}", method = { RequestMethod.PUT })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> putClassStudent(@PathVariable("classId") String classId,
			@PathVariable("studentId") String studentId) {
		return returnSuccess(teacherBusiness.putStudent2Class(studentId, classId));

	}

	@RequestMapping(value = "/classes/{classId}/students", method = { RequestMethod.GET })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<ClassStudentRefEntity>>> loadMembersOfClass(
			@PathVariable("classId") String classId, @RequestParam("index") int index, @RequestParam("size") int size) {
		DefaultPagingBody<ClassStudentRefEntity> res = new DefaultPagingBody<>(index, size);
		res.fill(teacherBusiness.loadClassStudents(classId, toPageRequestDescId(index, size)));
		return returnSuccess(res);
	}

	@RequestMapping(value = "/loadAllStudentOfClass", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<ClassStudentRefEntity>>> loadAllStudentOfClass(
			@RequestBody IdForm form) {

		String classId = form.getId();
		AccountEntity teacher = loadCurrentAccount();

		DefaultPagingBody<ClassStudentRefEntity> res = new DefaultPagingBody<>(1, 10);
		res.setTotal(0);
		res.setItems(Collections.emptyList());

		if (teacher == null || StringUtils.isAnyBlank(classId, teacher.getId())) {
			return returnSuccess(res);
		}

		List<ClassStudentRefEntity> list = teacherBusiness.loadAllClassMembers(classId);
		res.setItems(list);
		res.setTotal(list.size());

		return returnSuccess(res);
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/sendAwardsToStudent", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<Boolean>> sendAwardsToStudent(@RequestBody Map<String, Object> form) {
		// "awards":["8dc7a1ce-f869-493f-8371-c550ee093c9c","6b4b1d4d-d7e5-4c20-a2b6-b4ea1b861ebd"],"studentId":"f78f1822-ff15-47fa-9b54-083dd70ac2d4","teacherId":"4"
		List<String> awards = (List<String>) form.get("awards");
		String studentId = (String) form.get("studentId");
		String teacherId = loadCurrentAccount().getId();

		boolean res = teacherBusiness.sendAwards2Student(teacherId, studentId, awards);

		return returnSuccess(res);

	}

	/**
	 * 教师查看班级中的学生
	 * 
	 * @param user .
	 * @return .
	 */
	@RequestMapping(value = "/students/all", consumes = "application/json", method = { RequestMethod.POST })
	@Ignore
	public ResponseEntity<BaseRespEntity<DefaultPagingBody<IdNameDescIconForm>>> allStudents(
			@RequestBody PagableForm form) {

		DefaultPagingBody<IdNameDescIconForm> res = new DefaultPagingBody<IdNameDescIconForm>(form);

		String teacher_id = loadCurrentAccount().getId();
		Page<AccountEntity> page = teacherBusiness.loadAllStudent(teacher_id,
				form.toPageRequest(new Sort.Order(Direction.DESC, "id")));

		List<IdNameDescIconForm> list = new ArrayList<>();

		logDebug(String.valueOf(teacher_id));
		logDebug(String.valueOf(page));
		logDebug(String.valueOf(page.getContent()));

		page.getContent().forEach(it -> {
			IdNameDescIconForm cur = new IdNameDescIconForm();
			cur.setId(it.getId());
			cur.setName(it.getName());
			cur.setDesc(it.getAccountDesc());
			cur.setIcon(it.getImage());
			list.add(cur);
		});

		res.setItems(list);

		res.setTotal((int) page.getTotalElements());

		return returnSuccess(res);

	}

}
